/*
 * Copyright (c) 2022 Kirky
 * Licensed under the Open Software Licence, Version 3.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://opensource.org/licenses/osl-3.0.php
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lingeringdream.luciole.slice.fraction;

import com.lingeringdream.luciole.ResourceTable;
import com.lingeringdream.luciole.helper.generalDialog.GeneralButtonElement;
import com.lingeringdream.luciole.helper.generalDialog.GeneralDialogHelper;
import com.lingeringdream.luciole.helper.list.OptionListHelper;
import com.lingeringdream.luciole.helper.qrCode.QrHelper;
import com.lingeringdream.luciole.model.Constants;
import com.lingeringdream.luciole.slice.AboutUsSlice;
import com.lingeringdream.luciole.slice.AchieveSlice;
import com.lingeringdream.luciole.slice.MessageSlice;
import com.lingeringdream.luciole.slice.UserInfoSlice;
import com.squareup.picasso.Picasso;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.DataAbilityHelper;
import ohos.aafwk.ability.DataAbilityRemoteException;
import ohos.aafwk.ability.fraction.Fraction;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.*;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.dialog.CommonDialog;
import ohos.data.dataability.DataAbilityPredicates;
import ohos.data.resultset.ResultSet;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.utils.net.Uri;

import static com.lingeringdream.luciole.model.Constants.AVATARS_BASE_URI;

/**
 * 主页面-个人fraction
 *
 * @author Kirky
 * @version 1.0
 * @date 2022/4/28
 */
public class IndividualFraction extends Fraction {
    private final HiLogLabel TAG = new HiLogLabel(HiLog.LOG_APP, 0x13, IndividualFraction.class.getSimpleName());
    private final AbilitySlice slice;
    /**
     * 数据库访问helper
     */
    private DataAbilityHelper helper;
    private Component individualFraction;
    /**
     * 个人卡片
     */
    private DirectionalLayout detailCard;
    /**
     * 个人设置列表layout
     */
    private DirectionalLayout mSettingList;
    /**
     * 当前用户的uid
     */
    private String uid;


    public IndividualFraction(AbilitySlice slice) {
        this.slice = slice;
    }

    @Override
    protected Component onComponentAttached(LayoutScatter scatter, ComponentContainer container, Intent intent) {
        individualFraction = scatter.parse(ResourceTable.Layout_fraction_individual, container, false);
        mSettingList = individualFraction.findComponentById(ResourceTable.Id_individual_setting_list);
        initList();
        detailCard = individualFraction.findComponentById(ResourceTable.Id_individual_card_layout);
        if (detailCard != null) {
            initQrCode();
            initAvatars();

            helper = DataAbilityHelper.creator(slice);
            try {
                initPersonInfo();
            } catch (DataAbilityRemoteException e) {
                HiLog.info(TAG, e.getLocalizedMessage());
            }
        }

        return individualFraction;
    }

    /**
     * 初始化用户信息
     */
    private void initPersonInfo() throws DataAbilityRemoteException {
        Text username = detailCard.findComponentById(ResourceTable.Id_individual_uname);

//        构造查询条件
        DataAbilityPredicates predicates = new DataAbilityPredicates();
        predicates.isNotNull("password");
        try {
            String[] columns = new String[]{"uid", "uname"};
            ResultSet resultSet = helper.query(Uri.parse(Constants.TABLE_USER.getValue()), columns, predicates);
            if (resultSet == null || resultSet.getRowCount() == 0) {
                username.setText("星萤");
                initAchievement(null);
                HiLog.info(TAG, "query: resultSet is null or no result found");
                return;
            }
            resultSet.goToFirstRow();
            uid = resultSet.getString(resultSet.getColumnIndexForName("uid"));
            username.setText(resultSet.getString(resultSet.getColumnIndexForName("uname")));
            initAchievement(null);
        } catch (Exception e) {
            HiLog.error(TAG, "query: " + e.getMessage());
        } finally {
            helper.release();
        }
    }

    /**
     * 初始化成就栏
     */
    private void initAchievement(String achievementId) {
        Text achievement = detailCard.findComponentById(ResourceTable.Id_individual_achievement);
        if (achievementId == null) {
            achievement.setText("只为守护每一份绿色");
        } else {
            achievement.setText(achievementId);
        }
    }

    /**
     * 初始化QR
     */
    private void initQrCode() {
        Image qr = detailCard.findComponentById(ResourceTable.Id_individual_qr);
        if (uid != null && !uid.isEmpty()) {
            qr.setVisibility(Component.VISIBLE);
            QrHelper.Builder qrHelper = new QrHelper.Builder(this);
            qr.setClickedListener(component -> qrHelper.setContent(uid).show());
        }
    }

    /**
     * 初始化头像
     */
    private void initAvatars() {
        Image avatars = detailCard.findComponentById(ResourceTable.Id_individual_avatars);
        avatars.setCornerRadius(1000f);
        Picasso.get()
                .load(Uri.parse(AVATARS_BASE_URI + uid + "-avatars.png"))
                .error(ResourceTable.Media_avatars_default)
                .fit()
                .into(avatars);
        avatars.setClickedListener(component -> {
            Image image = new Image(this);
            image.setLayoutConfig(new ComponentContainer.LayoutConfig(
                    ComponentContainer.LayoutConfig.MATCH_PARENT, ComponentContainer.LayoutConfig.MATCH_PARENT
            ));
            ShapeElement element = new ShapeElement(this, ResourceTable.Graphic_bg_avtars_black);
            image.setBackground(element);
            image.setScaleMode(Image.ScaleMode.ZOOM_CENTER);
            Picasso.get()
                    .load(Uri.parse(AVATARS_BASE_URI + uid + "-avatars.png"))
                    .error(ResourceTable.Media_avatars_default)
                    .fit()
                    .into(image);

            CommonDialog dialog = new CommonDialog(this.getContext());
            dialog.setSize(ComponentContainer.LayoutConfig.MATCH_CONTENT, ComponentContainer.LayoutConfig.MATCH_CONTENT);
            dialog.setAlignment(LayoutAlignment.CENTER);
            dialog.setTransparent(true);
            dialog.setContentCustomComponent(image);
            dialog.setAutoClosable(true);
            dialog.show();

            image.setClickedListener(component1 -> dialog.remove());

        });
    }

    /**
     * 初始化列表item
     */
    private void initList() {
        OptionListHelper.Builder mHelper = new OptionListHelper.Builder(getContext());
        mHelper.setDirectionalLayout(mSettingList).setIcon(true)
                .addItem(ResourceTable.Graphic_ic_business_cards, "个人信息", listener -> {
//                    跳转个人信息slice
                    if (uid != null) {
                        Intent intent = new Intent();
                        intent.setParam("uid", uid);
                        slice.present(new UserInfoSlice(), intent);
                    } else {
                        suggestLogin();
                    }
                })
                .addItem(ResourceTable.Graphic_ic_account, "账号管理", listener -> {
//                    跳转账号管理slice
                    if (uid != null) {
                        Intent intent = new Intent();
                        intent.setParam("uid", uid);
                        slice.present(new UserInfoSlice(), intent);
                    } else {
                        suggestLogin();
                    }
                })
                .addItem(ResourceTable.Graphic_ic_message, "我的消息", listener -> {
//                    跳转消息slice
                    if (uid != null) {
                        Intent intent = new Intent();
                        intent.setParam("uid", uid);
                        slice.present(new MessageSlice(), intent);
                    } else {
                        suggestLogin();
                    }
                })
                .addItem(ResourceTable.Graphic_ic_achievement, "我的成就", listener -> {
//                    跳转我的成就slice
                    if (uid != null) {
                        Intent intent = new Intent();
                        intent.setParam("uid", uid);
                        slice.present(new AchieveSlice(), intent);
                    } else {
                        suggestLogin();
                    }
                })
                .addItem(ResourceTable.Graphic_ic_privacy, "隐私清单", listener -> {
//                    跳转隐私清单slice
                    Intent intent = new Intent();
                    slice.present(new MessageSlice(), intent);
                })
                .addItem(ResourceTable.Graphic_ic_settings, "通用设置", listener -> {
//                    跳转设置ability
                    Intent intent = new Intent();
                    Operation operation = new Intent.OperationBuilder().withDeviceId("")
                            .withBundleName(getBundleName())
                            .withAbilityName("com.lingeringdream.luciole.ability.SettingAbility")
                            .build();
                    intent.setOperation(operation);
                    slice.startAbility(intent);
                })
                .addItem(ResourceTable.Graphic_ic_aboutus, "关于我们", listener -> {
//                    跳转关于我们slice
                    Intent intent = new Intent();
                    slice.present(new AboutUsSlice(), intent);
                })
                .create();
    }

    /**
     * 建议登陆弹窗
     * 当前用户未进行登陆，无法获取后续操作
     */
    private void suggestLogin() {
        GeneralDialogHelper.Builder builder = new GeneralDialogHelper.Builder(getContext());
        builder.setAlignment(LayoutAlignment.BOTTOM)
                .setContent("当前用户未登录，是否登录？")
                .addButton("取消", GeneralButtonElement.TYPE_NORMAL, GeneralDialogHelper::remove)
                .addButton("登录", GeneralButtonElement.TYPE_ACCENT, dialog -> {
//                                    TODO 跳转登录页面

                    dialog.remove();
                })
                .create()
                .show();
    }
}